<?php
// +--------------------------------------------------------------------------------------------
// | Author: Admin <543423@qq.com>
// +--------------------------------------------------------------------------------------------
// | Copyright ThinkAdmin http://www.thinkadmin.cn All rights reserved.
// +--------------------------------------------------------------------------------------------

/**
 * +--------------------------------------------------------------------------------------------
 * | 角色模型
 * +--------------------------------------------------------------------------------------------
 * | 角色模型
 * +--------------------------------------------------------------------------------------------
 */
namespace Common\Model;
class SystemRoleModel extends CommonModel{
	public $onlyField = array('name'); //唯一字段
	//自动验证
	protected $_validate = array(

	array('name','1,16','{%NAME_LENGTH_ERROR_TIP}',2,'length'), // 长度判断

	array('name','require','{%NAME_NO_EMPTY_TIP}'), //名称不能为空

	array('name','is_format_name','{%NAME_FORMAT_TIP}',0,'function'), //名称正则检查格式

	);

	//自动完成
	protected $_auto = array (

	array('remark','get_safe_html',3,'function'), // 对remark字段在新增会更新的时候进行安全过滤

	array('remark','',2,'ignore'), // 对remark字段修改的时候如果留空忽略

	);

	//关联定义
	protected $_link = array(

	'SystemUserRole'=> array(  
           'mapping_type'=> 3,
           'class_name'=>'SystemUserRole',
           'foreign_key'=>'role_id',
           'mapping_name'=>'SystemUserRole',
	),

	'SystemRoleRules' =>array(
           'mapping_type'=> 3,
           'class_name'=>'SystemRoleRules',
           'foreign_key'=>'role_id',
           'mapping_name'=>'SystemRoleRules',
	),

	);

	/**
	 *
	 * 验证角色是否具有这些规则的权限
	 * @param $rules 验证规则 数组，支持多个
	 * @param $roleId 验证的角色id
	 * @return 返回存在规则的数据 如果返回false表示一个权限都没通过
	 */
	public function verifyAuth($rules=array(),	$roleId=false){
		//获取角色拥有的所有规则
		$roleRules = $this->getRoleRules($roleId);
		$list = array();
		foreach ($roleRules as $k=>$v){
			foreach ($rules as $k2=>$v2){
				if($v2 == $v['rules_rules']) $list[]=$v;
			}
		}
		return $list;
	}

	/**
	 *
	 * 根据角色id获取角色的权限规则
	 * @param $roleId 角色id
	 * @return array 角色规则列表
	 */
	public function getRoleRules($roleId = ''){
		if(empty($roleId)) return array();
		$rules = F($this->getModelName().'_Rules_'.$roleId,'', DATA_PATH.'./'.$this->getModelPrefix().'/'.$this->getModelName().'/Rules/');
		if($rules === false){ //没有缓存从数据获取
			$ruleRulesView = M('\Common\Model\ViewModel:'.$this->name); //继承视图模型
			$viewFields = $this->viewFields(M('SystemRoleRules'));
			$viewFields = array_merge($viewFields, $this->viewFields(M('SystemRules'),'rules_'));
			$viewFields['SystemRules']['_on'] = 'SystemRoleRules.rules_id=SystemRules.id';
			$ruleRulesView->setProperty("viewFields",$viewFields);
			$where['role_id'] = array('eq',$roleId);
			$where['rules_status'] = array('eq', 1);
			$rules = $ruleRulesView->where($where)->select();
			F($this->getModelName().'_Rules_'.$roleId,$rules,DATA_PATH.'./'.$this->getModelPrefix().'/'.$this->getModelName().'/Rules/');
		}
		return $rules ? $rules : array();
	}


	/**
	 *
	 * 获取角色菜单处理成不同格式
	 * @param $roleId  角色id
	 * @param $menuTypeId 菜单类型id
	 * @param $type  处理方式
	 * @return 返回对应处理方式的的数据
	 */
	public function getRoleMenu($roleId = '', $menuTypeId = '',$type='level',$pid = 0){
		$menu = F($this->getModelName().'_Menu_'.$roleId, '', DATA_PATH.'./'.$this->getModelPrefix().'/'.$this->getModelName().'/Menu/');  //获取缓存
		if(!isset($menu[$menuTypeId][$type][$pid])){  //如果没有该角色的缓存菜单尝试从数据中获取
			$roleMenu = $this->getRoleMenuList($roleId, $menuTypeId);
			if($type =='level'){
				$menu[$menuTypeId][$type][$pid] = $roleMenu ? array_filter(menutree($roleMenu,$pid)) : array();
			}
			F($this->getModelName().'_Menu_'.$roleId,$menu, DATA_PATH.'./'.$this->getModelPrefix().'/'.$this->getModelName().'/Menu/');  //获取缓存
		}
		return $menu[$menuTypeId][$type][$pid];
	}

	/**
	 * 根据角色获取菜单，未处理,未缓存，应为各个模块下得菜单可能需要处理的方式不一样，所以这里返回原生查询数据
	 * @$roleId 角色id
	 * @$menuTypeId 菜单类型id
	 */
	private function getRoleMenuList($roleId="", $menuTypeId = ""){
		if(empty($roleId)) return false;
		$menu = M('SystemMenu');
		$where['status'] = array('eq',1);
		$where['menutype_id'] = array('eq',$menuTypeId);
		$allMenu = $menu->where($where)->order('sort asc')->field('id as menu_id, name as menu_name,url as menu_url, color as menu_color, bold as menu_bold, pid as menu_pid, sort as menu_sort, status as menu_status, fun as menu_fun, remark as menu_remark,  target as menu_target, rules as menu_rules,rulestype as menu_rulestype, menutype_id')->select();
		if($roleId == C('ADMIN_ROLE_ID') || !C('IS_AUTH')){  //如果是超级管理员或者系统没有要求权限直接返回所有菜单
			return $allMenu;
		}else{  //角色菜单处理
			$roleMenu = array();  //构建一个新的菜单数组
			foreach($allMenu	as $k=>$v){
				if(empty($v['menu_rules'])){  //如果菜单不存在规则表示所有角色通用
					$roleMenu[] = $v;
				}else{	//检测用户是否存在该菜单的规则
					if(empty($v['menu_rulestype'])) $v['menu_rulestype'] = 'and';
					if(RULES_AUTH(explode(',', $v['menu_rules']),$v['menu_rulestype'],$roleId)){
						$roleMenu[] = $v;
					}
				}
			}
			return $roleMenu;
		}
	}

}